package com.market.fleamarket.service;

import com.market.fleamarket.entity.Cart;
import com.market.fleamarket.entity.Order;
import com.market.fleamarket.entity.Product;
import com.market.fleamarket.entity.User;
import com.market.fleamarket.repository.CartRepository;
import com.market.fleamarket.repository.OrderRepository;
import com.market.fleamarket.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

@Service
public class CartService {
    @Autowired
    private CartRepository cartRepository;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;

    public Cart save(Cart cart) {
        return cartRepository.save(cart);
    }

    public List<Cart> findAll() {
        return cartRepository.findAll();
    }

    public Optional<Cart> findById(Long id) {
        return cartRepository.findById(id);
    }

    public void deleteById(Long id) {
        cartRepository.deleteById(id);
    }

    public List<Cart> findByUserId(Long userId) {
        List<Cart> allCarts = cartRepository.findAll();
        return allCarts.stream()
                .filter(cart -> cart.getUser() != null && cart.getUser().getId().equals(userId))
                .collect(java.util.stream.Collectors.toList());
    }

    @Transactional
    public Order checkoutCart(User user) {
        List<Cart> cartList = findByUserId(user.getId());
        if (cartList.isEmpty()) throw new RuntimeException("购物车为空");
        Cart cart = cartList.get(0); // 简化为单商品结算
        Product product = cart.getProduct();

        // 检查商品是否有效
        if (!product.isValid()) throw new RuntimeException("商品已下架或过期");

        // 检查库存是否足够
        if (!productService.checkStock(product.getId(), cart.getQuantity())) {
            throw new RuntimeException("商品库存不足");
        }

        BigDecimal total = product.getPrice().multiply(BigDecimal.valueOf(cart.getQuantity()));
        Order order = new Order();
        order.setBuyer(user);
        order.setProduct(product);
        order.setQuantity(cart.getQuantity());
        order.setTotalPrice(total);

        // 使用OrderService创建订单，会自动减少库存
        Order savedOrder = orderService.createOrder(order);

        // 删除购物车项
        cartRepository.delete(cart);

        return savedOrder;
    }
} 